package com.zjw.dao.impl;

import com.zjw.dao.BaseDao;
import com.zjw.dao.NoteDao;
import com.zjw.entity.Note;
import com.zjw.utils.ConnectionUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: note
 * @package: com.zjw.dao.impl
 * @className: NoteDaoImpl
 * @author: 翟
 * @date: 2025/4/3 11:50
 */

public class NoteDaoImpl extends BaseDao implements NoteDao {

    public NoteDaoImpl(Connection connection) {
        super(connection);
    }

    @Override
    public int insertNote(Note note) throws SQLException {
        String sql = "insert into note(note_id , note_title, note_content, note_creation_date) values(null , ? , ? , ?)";
        return executeUpdate(sql , note.getNoteTitle() , note.getNoteContent() , note.getNoteCreationDate());
    }

    @Override
    public List<Note> selectNoteByPage(int index, int pageSize) throws SQLException {
        String sql = "select note_id , note_title from note limit ? , ?";
        List<Note> list = new ArrayList<>();
        ResultSet resultSet = null;
        try {
            resultSet = executeQuery(sql , index , pageSize);
            while (resultSet.next()) {
                Note note = new Note();
                note.setNoteId(resultSet.getInt("note_id"));
                note.setNoteTitle(resultSet.getNString("note_title"));
                list.add(note);
            }
        } finally {
            ConnectionUtil.closeALL(resultSet , null , null);
        }
        return list;
    }

    @Override
    public int selectNoteCount() throws SQLException {
        String sql = "select count(1) from note";
        ResultSet resultSet = executeQuery(sql);
        return resultSet.next()? resultSet.getInt(1) : 0;
    }

    @Override
    public Note selectNoteById(int id) throws SQLException {
        String sql = "select note_id , note_title , note_content , note_creation_date from note where note_id = ?";
        ResultSet resultSet = null;
        Note note = null;
        try {
            resultSet = executeQuery(sql , id);
            if (resultSet.next()){
                note = new Note();
                note.setNoteId(resultSet.getInt("note_id"));
                note.setNoteTitle(resultSet.getNString("note_title"));
                note.setNoteContent(resultSet.getNString("note_content"));
                note.setNoteCreationDate(resultSet.getDate("note_creation_date"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return note;
    }
}
